package com.neusoft.orcode.controller;

import com.alibaba.fastjson.JSON;
import com.neusoft.orcode.Service.PatientService;
import com.neusoft.orcode.Utils.BouncyCastleRSA;
import com.neusoft.orcode.info.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class QrcodeController {

    @Autowired
    PatientService patientService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    // http://127.0.0.1:8080/qrcode
    // 接收患者信息后转换为二维码
    @RequestMapping("/qrcode")
    public String qrcode(Model model, @RequestParam("name") String name, @RequestParam("id") String id) {
        // 设置uuid为auth_id
        String auth_id = UUID.randomUUID().toString().replace("-", "");
        PatientInfo patient = new PatientInfo(id,name,"","","",auth_id,0);
        // 获取患者信息写入redis，保存时间为3分钟
        redisTemplate.opsForValue().set(auth_id, JSON.toJSONString(patient), 600, TimeUnit.SECONDS);
        System.out.println(auth_id);
        // 包装并返回auth_id
        QrCodeInfo qrCodeInfo = new QrCodeInfo(auth_id);
        model.addAttribute("qrCodeInfo", qrCodeInfo);
        HashMap params = new HashMap();
        params.put("organCode", "healthOne_empi");
        params.put("personId", id);
        params.put("docIdCard", "123456");
        params.put("adminDivisionCode", "123456");
        params.put("medicalStatus", "1");
        params.put("appId", "saca_GvmMRkJgx3");
        params.put("cardType" , "02");
        try {
            String url = BouncyCastleRSA.encryptedString(params);
            model.addAttribute("url", url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "qrcode";
    }

    // http://127.0.0.1:8080/getPatientInfo
    // EHR_授权信息查询：接收auth_id,以json返回患者信息。
    @PostMapping(value = "/getPatientInfo", produces = "application/json")
    @ResponseBody
    public R getPatientInfo(@RequestParam("auth_id") String authId) {
        PatientInfo patientInfo = patientService.getPatientById(authId);
        System.out.println(patientInfo);
        if(patientInfo == null) {
            return R.error("数据过期，请重新扫码申请");
        }
        R r = R.ok("请求到达");
        PatientInfo[] patientInfos= new PatientInfo[1];
        patientInfos[0] = patientInfo;
        r.setData(patientInfos);
        return r;
    }

    /**
     * 授权接口(ehr_authorized_upd)
     *
     * 接收参数:
     *  auth_id	调用记录ID
     *  auth_status	授权标记(1： 授权 2： 拒绝 )
     *  cert_number	患者证件号码
     *  name	患者姓名
     *  detail	患者手机号码
     *
     * 返回参数：
     *  result_code
     *      1：授权写入成功(同意授权 拒绝授权)
     *      2：授权超时(超过三分钟 重新授权)
     */
    // http://127.0.0.1:8080/ehr_authorized_upd
    @PostMapping(value = "/ehr_authorized_upd", produces = "application/json")
    @ResponseBody
    public R a(@RequestParam("auth_id") String authId ,@RequestParam("auth_status") int authStatus) {
        PatientInfo patient = patientService.getPatientById(authId);
        if(patient == null) {
            return R.error("数据过期，授权失败").put("auth_id", authId).put("result_code", 2);
        }
        patient.setAuth_status(authStatus);
        redisTemplate.opsForValue().getAndSet(authId, JSON.toJSONString(patient));
        System.out.println("修改成功");
        R r = R.ok();
        r.put("auth_id", authId).put("result_code", 1);
        return r;
    }

//    鉴权接口
    @PostMapping(value = "/getAuth_status", produces = "application/json")
    @ResponseBody
    public int getAuth_status(@RequestParam("auth_id") String authId) {
        PatientInfo patientInfo = patientService.getPatientById(authId);
        if(patientInfo == null) {
            return -1;
        }
        System.out.println(patientInfo);
        return patientInfo.getAuth_status();
    }



}
